package com.ruoyi.factory.staffSafe.service.impl;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.ruoyi.factory.common.utils.IdGen;
import com.ruoyi.factory.staffSafe.domain.StaffType;
import com.ruoyi.factory.staffSafe.domain.StaffsafeCredential;
import com.ruoyi.factory.staffSafe.domain.StaffsafeInfo;
import com.ruoyi.factory.staffSafe.domain.StaffsafeRecord;
import com.ruoyi.factory.staffSafe.mapper.StaffTypeMapper;
import com.ruoyi.factory.staffSafe.mapper.StaffsafeInfoMapper;
import com.ruoyi.factory.staffSafe.service.IStaffsafeInfoService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


import javax.servlet.http.HttpServletResponse;

/**
 * 培训档案人员信息Service业务层处理
 * 
 * @author ljj
 * @date 2024-04-15
 */
@Service
public class StaffsafeInfoServiceImpl implements IStaffsafeInfoService
{
    @Autowired
    private StaffsafeInfoMapper staffsafeInfoMapper;

    @Autowired
    private StaffTypeMapper staffTypeMapper;

    @Value("${staffsafe.templateurl.zy}")
    private String templatezy;

    @Value("${staffsafe.templateurl.gl}")
    private String templategl;

    @Value("${staffsafe.templateurl.tz}")
    private String templatetz;

    @Value("${staffsafe.templateurl.qt}")
    private String templateqt;

    @Value("${staffsafe.lswjdz}")
    private String lswjdz;

    /**
     * 查询培训档案人员信息
     * 
     * @param id 培训档案人员信息主键
     * @return 培训档案人员信息
     */
    @Override
    public StaffsafeInfo selectStaffsafeInfoById(String id)
    {
        return staffsafeInfoMapper.selectStaffsafeInfoById(id);
    }

    /**
     * 查询培训档案人员信息列表
     * 
     * @param staffsafeInfo 培训档案人员信息
     * @return 培训档案人员信息
     */
    @Override
    public List<StaffsafeInfo> selectStaffsafeInfoList(StaffsafeInfo staffsafeInfo)
    {
        List<StaffsafeInfo> staffsafeInfos = staffsafeInfoMapper.selectStaffsafeInfoList2(staffsafeInfo);
//        List<StaffsafeInfo> staffsafeInfos = staffsafeInfoMapper.selectStaffsafeInfoList(staffsafeInfo);
        //处理数据
        return handStaffData(staffsafeInfos);
    }

    /**
     * 查询培训档案人员信息列表
     *
     * @param staffsafeInfo 培训档案人员信息
     * @return 培训档案人员信息
     */
    @Override
    public List<StaffsafeInfo> exprotStaffsafeInfoList(StaffsafeInfo staffsafeInfo)
    {
        List<StaffsafeInfo> item = staffsafeInfoMapper.selectStaffsafeInfoList3(staffsafeInfo);
        List<String> list = new ArrayList<>();
        StaffsafeInfo param = new StaffsafeInfo();
        for (StaffsafeInfo info : item) {
            list.add(info.getId());
//            param.setList(list);
        }

        List<StaffsafeInfo> staffsafeInfos = staffsafeInfoMapper.selectStaffsafeInfoList4(staffsafeInfo,list);
//        List<StaffsafeInfo> staffsafeInfos = staffsafeInfoMapper.selectStaffsafeInfoList(staffsafeInfo);
//        处理数据
        return handStaffData(staffsafeInfos);
    }

    public void setinfogl(HttpServletResponse response, List<StaffsafeInfo> list, String resultType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SimpleDateFormat sdfqz = new SimpleDateFormat("yyyy.MM");
        List<Map<String, Object>> listm = new ArrayList<>();
        for (StaffsafeInfo staffsafeInfo : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("ucode", staffsafeInfo.getUserCode());
            map.put("username", staffsafeInfo.getUsername());
            map.put("sex", staffsafeInfo.getSex());
            map.put("usecardid", staffsafeInfo.getUserCardId());
            map.put("zw", staffsafeInfo.getStaffType().getTypename());
            map.put("byyx", staffsafeInfo.getSchool());
            map.put("sxzy", staffsafeInfo.getProfessional());
            map.put("lxdh", staffsafeInfo.getPhone());
            //证书
            List<StaffsafeCredential> staffsafeCredentialList = staffsafeInfo.getStaffsafeCredentialList();
            for (StaffsafeCredential staffsafeCredential : staffsafeCredentialList) {
                Date starttime = staffsafeCredential.getStarttime();
                Date endtime = staffsafeCredential.getEndtime();
                String creid = staffsafeCredential.getCreid();
                if (null != starttime && null != endtime && StringUtils.isNotEmpty(creid)){
                    String format = sdfqz.format(starttime);
                    String format1 = sdfqz.format(endtime);
                    String zsyxqzrq = (String) map.get("zsyxqzrq");
                    String aqzgzsid = (String) map.get("aqzgzsid");
                    if(StringUtils.isNotEmpty(zsyxqzrq) && StringUtils.isNotEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",zsyxqzrq+"/"+format+"~"+format1);
                        map.put("aqzgzsid",creid+"/"+creid);
                    }else if(StringUtils.isEmpty(zsyxqzrq) && StringUtils.isEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",format+"~"+format1);
                        map.put("aqzgzsid",creid);
                    }
                }
            }
            //培训记录
            List<Map<String, Object>> alarms = new ArrayList<>();
            List<StaffsafeRecord> staffsafeRecordList = staffsafeInfo.getStaffsafeRecordList();
            for (StaffsafeRecord staffsafeRecord : staffsafeRecordList) {
                Map<String, Object> alarm = new HashMap<>();
                //培训时间
                Date recordtime = staffsafeRecord.getRecordtime();
                if(null != recordtime){
                    String format = sdf.format(recordtime);
                    alarm.put("pxsj",format);
                }
                //培训内容
                String recordtitle = staffsafeRecord.getRecordtitle();
                if(StringUtils.isNotEmpty(recordtitle)){
                    alarm.put("pxnr",recordtitle);
                }
                //培训方式
                String recordtype = staffsafeRecord.getRecordtype();
                if(StringUtils.isNotEmpty(recordtype)){
                    alarm.put("pxfs",recordtype);
                }
                //课时数
                String classhour = staffsafeRecord.getClasshour();
                if(StringUtils.isNotEmpty(classhour)){
                    alarm.put("kss",classhour);
                }
                //成绩
                BigDecimal score = staffsafeRecord.getScore();
                String recordresult = staffsafeRecord.getRecordresult();

                if(StringUtils.isNotEmpty(recordresult)){
                    alarm.put("cj",recordresult);
                }
                if(null != score && score.compareTo(new BigDecimal(0)) != 0){
                    alarm.put("cj",score.setScale(0, BigDecimal.ROUND_DOWN));
                }
                if(StringUtils.isNotEmpty(resultType)){
                    alarm.put("cj","合格");
                }
                //授课教师
                String teacher = staffsafeRecord.getTeacher();
                if(StringUtils.isNotEmpty(teacher)){
                    alarm.put("skjs",teacher);
                }
                alarms.add(alarm);
            }
            map.put("alarms",alarms);
            listm.add(map);
        }
        String str = UUID.randomUUID().toString()+".docx";
        String templatePath = templategl;
        easyPoiExport(response,templatePath, lswjdz, str, listm);
    }
    public void setinfozy(HttpServletResponse response, List<StaffsafeInfo> list, String resultType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SimpleDateFormat sdfqz = new SimpleDateFormat("yyyy.MM");
        List<Map<String, Object>> listm = new ArrayList<>();
        for (StaffsafeInfo staffsafeInfo : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("ucode", staffsafeInfo.getUserCode());
            map.put("username", staffsafeInfo.getUsername());
            map.put("sex", staffsafeInfo.getSex());
            map.put("usecardid", staffsafeInfo.getUserCardId());
            map.put("zw", staffsafeInfo.getStaffType().getTypename());
            map.put("byyx", staffsafeInfo.getSchool());
            map.put("sxzy", staffsafeInfo.getProfessional());
            map.put("lxdh", staffsafeInfo.getPhone());
            //证书
            List<StaffsafeCredential> staffsafeCredentialList = staffsafeInfo.getStaffsafeCredentialList();
            for (StaffsafeCredential staffsafeCredential : staffsafeCredentialList) {
                Date starttime = staffsafeCredential.getStarttime();
                Date endtime = staffsafeCredential.getEndtime();
                String creid = staffsafeCredential.getCreid();
                if (null != starttime && null != endtime && StringUtils.isNotEmpty(creid)){
                    String format = sdfqz.format(starttime);
                    String format1 = sdfqz.format(endtime);
                    String zsyxqzrq = (String) map.get("zsyxqzrq");
                    String aqzgzsid = (String) map.get("aqzgzsid");
                    if(StringUtils.isNotEmpty(zsyxqzrq) && StringUtils.isNotEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",zsyxqzrq+"/"+format+"~"+format1);
                        map.put("aqzgzsid",creid+"/"+creid);
                    }else if(StringUtils.isEmpty(zsyxqzrq) && StringUtils.isEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",format+"~"+format1);
                        map.put("aqzgzsid",creid);
                    }
                }
            }
            //培训记录
            List<Map<String, Object>> alarms = new ArrayList<>();
            List<StaffsafeRecord> staffsafeRecordList = staffsafeInfo.getStaffsafeRecordList();
            for (StaffsafeRecord staffsafeRecord : staffsafeRecordList) {
                Map<String, Object> alarm = new HashMap<>();
                //培训时间
                Date recordtime = staffsafeRecord.getRecordtime();
                if(null != recordtime){
                    String format = sdf.format(recordtime);
                    alarm.put("pxsj",format);
                }
                //培训内容
                String recordtitle = staffsafeRecord.getRecordtitle();
                if(StringUtils.isNotEmpty(recordtitle)){
                    alarm.put("pxnr",recordtitle);
                }
                //培训方式
                String recordtype = staffsafeRecord.getRecordtype();
                if(StringUtils.isNotEmpty(recordtype)){
                    alarm.put("pxfs",recordtype);
                }
                //课时数
                String classhour = staffsafeRecord.getClasshour();
                if(StringUtils.isNotEmpty(classhour)){
                    alarm.put("kss",classhour);
                }
                //成绩
                BigDecimal score = staffsafeRecord.getScore();
                String recordresult = staffsafeRecord.getRecordresult();
//                String recordresfalse = staffsafeRecord.getRecordresfalse();

                if(StringUtils.isNotEmpty(recordresult)){
                    alarm.put("cj",recordresult);
                }
                if(null != score && score.compareTo(new BigDecimal(0)) != 0){
                    alarm.put("cj",score.setScale(0, BigDecimal.ROUND_DOWN));
                }
                if(StringUtils.isNotEmpty(resultType)){
                    alarm.put("cj","合格");
                }
                //授课教师
                String teacher = staffsafeRecord.getTeacher();
                if(StringUtils.isNotEmpty(teacher)){
                    alarm.put("skjs",teacher);
                }
                alarms.add(alarm);
            }
            map.put("alarms",alarms);
            listm.add(map);
        }
        String str = UUID.randomUUID().toString()+".docx";
        String templatePath = templatezy;
        easyPoiExport(response,templatePath, lswjdz, str, listm);
    }
    public void setinfotz(HttpServletResponse response, List<StaffsafeInfo> list, String resultType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SimpleDateFormat sdfqz = new SimpleDateFormat("yyyy.MM");
        List<Map<String, Object>> listm = new ArrayList<>();
        for (StaffsafeInfo staffsafeInfo : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("ucode", staffsafeInfo.getUserCode());
            map.put("username", staffsafeInfo.getUsername());
            map.put("sex", staffsafeInfo.getSex());
            map.put("usecardid", staffsafeInfo.getUserCardId());
            map.put("lxdh", staffsafeInfo.getPhone());

            //证书
            List<StaffsafeCredential> staffsafeCredentialList = staffsafeInfo.getStaffsafeCredentialList();
            for (StaffsafeCredential staffsafeCredential : staffsafeCredentialList) {
                Date starttime = staffsafeCredential.getStarttime();
                Date endtime = staffsafeCredential.getEndtime();
                Calendar instance = Calendar.getInstance();
                String creid = staffsafeCredential.getCreid();
                String crepro = staffsafeCredential.getCrepro();
                String edudep = staffsafeCredential.getEdudep();
                if (null != starttime && null != endtime && StringUtils.isNotEmpty(creid) && StringUtils.isNotEmpty(crepro) && StringUtils.isNotEmpty(edudep)) {
                    String format = sdfqz.format(starttime);
                    String format1 = sdfqz.format(endtime);
                    instance.setTime(endtime);
                    instance.add(Calendar.MONTH,-3);
                    Date time = instance.getTime();
                    String format2 = sdf.format(time);
                    String zsyxqzrq = (String) map.get("zsyxqzrq");
                    String aqzgzsid = (String) map.get("aqzgzsid");
                    String fsrq = (String) map.get("fsrq");
                    String aqzgzslb = (String) map.get("aqzgzslb");
                    String pxjg = (String) map.get("pxjg");
                    if(StringUtils.isNotEmpty(zsyxqzrq) && StringUtils.isNotEmpty(aqzgzsid) && StringUtils.isNotEmpty(fsrq) && StringUtils.isNotEmpty(aqzgzslb) && StringUtils.isNotEmpty(pxjg)){
                        map.put("zsyxqzrq",zsyxqzrq+"/"+format+"~"+format1);
                        map.put("aqzgzsid",aqzgzsid+"/"+creid);
                        map.put("fsrq",fsrq+"/"+format2);
                        map.put("aqzgzslb",aqzgzslb+"/"+crepro);
                        map.put("aqzgzspro",aqzgzslb+"/"+crepro);
                        map.put("pxjg",pxjg+"/"+edudep);
                        map.put("fzjg",pxjg+"/"+edudep);
                    }else if(StringUtils.isEmpty(zsyxqzrq) && StringUtils.isEmpty(aqzgzsid) && StringUtils.isEmpty(fsrq) && StringUtils.isEmpty(aqzgzslb) && StringUtils.isEmpty(pxjg)){
                        map.put("zsyxqzrq",format+"~"+format1);
                        map.put("aqzgzsid",creid);
                        map.put("fsrq",format2);
                        map.put("aqzgzslb",crepro);
                        map.put("aqzgzspro",crepro);
                        map.put("pxjg",edudep);
                        map.put("fzjg",edudep);
                    }

                }
            }
            //培训记录
            List<Map<String, Object>> alarms = new ArrayList<>();
            List<StaffsafeRecord> staffsafeRecordList = staffsafeInfo.getStaffsafeRecordList();
            for (StaffsafeRecord staffsafeRecord : staffsafeRecordList) {
                Map<String, Object> alarm = new HashMap<>();
                //培训时间
                Date recordtime = staffsafeRecord.getRecordtime();
                if(null != recordtime){
                    String format = sdf.format(recordtime);
                    alarm.put("pxsj",format);
                }
                //培训内容
                String recordtitle = staffsafeRecord.getRecordtitle();
                if(StringUtils.isNotEmpty(recordtitle)){
                    alarm.put("pxnr",recordtitle);
                }
                //培训方式
                String recordtype = staffsafeRecord.getRecordtype();
                if(StringUtils.isNotEmpty(recordtype)){
                    alarm.put("pxfs",recordtype);
                }
                //课时数
                String classhour = staffsafeRecord.getClasshour();
                if(StringUtils.isNotEmpty(classhour)){
                    alarm.put("kss",classhour);
                }
                //成绩
                BigDecimal score = staffsafeRecord.getScore();
                String recordresult = staffsafeRecord.getRecordresult();

                if(StringUtils.isNotEmpty(recordresult)){
                    alarm.put("cj",recordresult);
                }
                if(null != score && score.compareTo(new BigDecimal(0)) != 0){
                    alarm.put("cj",score.setScale(0, BigDecimal.ROUND_DOWN));
                }
                if(StringUtils.isNotEmpty(resultType)){
                    alarm.put("cj","合格");
                }
                //授课教师
                String teacher = staffsafeRecord.getTeacher();
                if(StringUtils.isNotEmpty(teacher)){
                    alarm.put("skjs",teacher);
                }
                alarms.add(alarm);
            }
            map.put("alarms",alarms);
            listm.add(map);
        }
        String str = UUID.randomUUID().toString()+".docx";
        String templatePath = templatetz;
        easyPoiExport(response,templatePath, lswjdz, str, listm);
    }
    public void setinfoqt(HttpServletResponse response, List<StaffsafeInfo> list, String resultType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SimpleDateFormat sdfqz = new SimpleDateFormat("yyyy.MM");
        List<Map<String, Object>> listm = new ArrayList<>();
        for (StaffsafeInfo staffsafeInfo : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("ucode", staffsafeInfo.getUserCode());
            map.put("username", staffsafeInfo.getUsername());
            map.put("sex", staffsafeInfo.getSex());
            map.put("usecardid", staffsafeInfo.getUserCardId());
            map.put("zw", staffsafeInfo.getStaffType().getTypename());
            map.put("byyx", staffsafeInfo.getSchool());
            map.put("sxzy", staffsafeInfo.getProfessional());
            map.put("lxdh", staffsafeInfo.getPhone());
            map.put("zgsf", staffsafeInfo.getPost());
            map.put("gzgw", staffsafeInfo.getDepname());
            Date jointime = staffsafeInfo.getJointime();
            if(null != jointime){
                map.put("rcsj", sdf.format(jointime));
            }

            //证书
            List<StaffsafeCredential> staffsafeCredentialList = staffsafeInfo.getStaffsafeCredentialList();
            for (StaffsafeCredential staffsafeCredential : staffsafeCredentialList) {
                Date starttime = staffsafeCredential.getStarttime();
                Date endtime = staffsafeCredential.getEndtime();
                String creid = staffsafeCredential.getCreid();
                if (null != starttime && null != endtime && StringUtils.isNotEmpty(creid)){
                    String format = sdfqz.format(starttime);
                    String format1 = sdfqz.format(endtime);
                    String zsyxqzrq = (String) map.get("zsyxqzrq");
                    String aqzgzsid = (String) map.get("aqzgzsid");
                    if(StringUtils.isNotEmpty(zsyxqzrq) && StringUtils.isNotEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",zsyxqzrq+"/"+format+"~"+format1);
                        map.put("aqzgzsid",creid+"/"+creid);
                    }else if(StringUtils.isEmpty(zsyxqzrq) && StringUtils.isEmpty(aqzgzsid)){
                        map.put("zsyxqzrq",format+"~"+format1);
                        map.put("aqzgzsid",creid);
                    }

                }
            }
            //培训记录
            List<Map<String, Object>> alarms = new ArrayList<>();
            List<StaffsafeRecord> staffsafeRecordList = staffsafeInfo.getStaffsafeRecordList();
            for (StaffsafeRecord staffsafeRecord : staffsafeRecordList) {
                Map<String, Object> alarm = new HashMap<>();
                //培训时间
                Date recordtime = staffsafeRecord.getRecordtime();
                if(null != recordtime){
                    String format = sdf.format(recordtime);
                    alarm.put("pxsj",format);
                }
                //培训内容
                String recordtitle = staffsafeRecord.getRecordtitle();
                if(StringUtils.isNotEmpty(recordtitle)){
                    alarm.put("pxnr",recordtitle);
                }
                //培训方式
                String recordtype = staffsafeRecord.getRecordtype();
                if(StringUtils.isNotEmpty(recordtype)){
                    alarm.put("pxfs",recordtype);
                }
                //课时数
                String classhour = staffsafeRecord.getClasshour();
                if(StringUtils.isNotEmpty(classhour)){
                    alarm.put("kss",classhour);
                }
                //成绩
                BigDecimal score = staffsafeRecord.getScore();
                String recordresult = staffsafeRecord.getRecordresult();

                if(StringUtils.isNotEmpty(recordresult)){
                    alarm.put("cj",recordresult);
                }
                if(null != score && score.compareTo(new BigDecimal(0)) != 0){
                    alarm.put("cj",score.setScale(0, BigDecimal.ROUND_DOWN));
                }
                if(StringUtils.isNotEmpty(resultType)){
                    alarm.put("cj","合格");
                }
                //授课教师
                String teacher = staffsafeRecord.getTeacher();
                if(StringUtils.isNotEmpty(teacher)){
                    alarm.put("skjs",teacher);
                }
                alarms.add(alarm);
            }
            map.put("alarms",alarms);
            listm.add(map);
        }
        String str = UUID.randomUUID().toString()+".docx";
        String templatePath = templateqt;
        easyPoiExport(response,templatePath, lswjdz, str, listm);
    }
    @Override
    public void downloadword(HttpServletResponse response, List<StaffsafeInfo> list, String staffType, String resultType)
    {
        //设置模板路径 根据类型分发
        if("0".equals(staffType)){
            setinfozy(response, list, resultType);
        }else if("1".equals(staffType)){
            setinfogl(response, list, resultType);
        }else if("2".equals(staffType)){
            setinfotz(response, list, resultType);
        }else if("3".equals(staffType)){
            setinfoqt(response, list, resultType);
        }
    }
    public void easyPoiExport(HttpServletResponse response, String templatePath, String tempDir, String filename, List<Map<String, Object>> list) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(tempDir, "临时文件路径不能为空");
        Assert.notNull(filename, "文件名称不能为空");
        Assert.isTrue(filename.endsWith(".docx"), "文件名称仅支持docx格式");
        Assert.isTrue(!list.isEmpty(),"该时间培训内容为空");

        if (!tempDir.endsWith("/")) {
            tempDir = tempDir + File.separator;
        }

        File file = new File(tempDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
//            String userAgent = request.getHeader("user-agent").toLowerCase();
//            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
//                filename = URLEncoder.encode(filename, "UTF-8");
//            } else {
//                filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
//            }

            XWPFDocument document = WordExportUtil.exportWord07(templatePath, list);
            String tempPath = tempDir + filename;
            FileOutputStream out = new FileOutputStream(tempPath);
            document.write(out);

//            InputStream in = new FileInputStream("path_to_your_word_file.docx");
//            XWPFDocument document = new XWPFDocument(in);

            // 检查每个段落
//            for (int i = 0; i < document.getParagraphs().size(); i++) {
//                XWPFParagraph paragraph = document.getParagraphs().get(i);
//                String text = paragraph.getText();
//
//                // 如果段落为空或者只包含空格，则删除该段落
//                if (text == null || text.trim().isEmpty()) {
//                    document.removeBodyElement(i);
//                    i--; // 因为已经删除了一个元素，所以索引要回退
//                }
//            }

            // 输出到新文件
//            FileOutputStream out = new FileOutputStream("path_to_output_file.docx");
            document.write(out);
            //关闭线程占用
            document.close();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            String filenames = tempDir + filename;
            down(response,filenames);
            deleteTempFile(tempDir, filename);
        }

    }

    public void down(HttpServletResponse response, String pathstr) {
        try {
            // 获取服务器文件
            File file = new File(pathstr);
            InputStream ins = new FileInputStream(file);
            /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
            response.setContentType("multipart/form-data");
            /* 设置文件头：最后一个参数是设置下载文件名 */
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }



    /**
     * 删除临时生成的文件
     */
    public void deleteTempFile(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File f = new File(filePath);
        file.delete();
        f.delete();
    }

    /**
     * @author: Liujiaji
     * @date: 2024/4/18 11:25
     * @description: TODO 导出数据之前对数据进行处理
     * @param: [staffsafeInfos]
     * @return: java.util.List<com.ruoyi.factory.staffSafe.domain.StaffsafeInfo>
     **/
    public List<StaffsafeInfo> handStaffData(List<StaffsafeInfo> staffsafeInfos){
        for (StaffsafeInfo info : staffsafeInfos) {
            List<StaffsafeCredential> staffsafeCredentialList = info.getStaffsafeCredentialList();
            for (StaffsafeCredential staffsafeCredential : staffsafeCredentialList) {
                String credentialname = staffsafeCredential.getCrepro();
                String creid = staffsafeCredential.getCreid();
                Date starttime = staffsafeCredential.getStarttime();
                Date endtime = staffsafeCredential.getEndtime();
                if(StringUtils.isNotEmpty(credentialname)){
                    if(StringUtils.isNotEmpty(info.getCredentialname())){
                        info.setCredentialname(info.getCredentialname()+"/"+credentialname);
                    }else{
                        info.setCredentialname(credentialname);
                    }
                }

                if(StringUtils.isNotEmpty(creid)){{
                    if(StringUtils.isNotEmpty(info.getCreid())){
                        info.setCreid(info.getCreid()+"/"+creid);
                    }else{
                        info.setCreid(creid);
                    }
                }}

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if(null != starttime){
                    String sformat = sdf.format(starttime);
                    if(StringUtils.isNotEmpty(info.getStarttime())){
                        info.setStarttime(info.getStarttime()+"/"+sformat);
                    }else{
                        info.setStarttime(sformat);
                    }
                }

                if(null !=endtime){
                    String eformat = sdf.format(endtime);
                    if(StringUtils.isNotEmpty(info.getEndtime())){
                        info.setEndtime(info.getEndtime()+"/"+eformat);
                    }else{
                        info.setEndtime(eformat);
                    }
                }

            }

        }
        return staffsafeInfos;
    }

    /**
     * 新增培训档案人员信息
     * 
     * @param staffsafeInfo 培训档案人员信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertStaffsafeInfo(StaffsafeInfo staffsafeInfo)
    {
        int rows = staffsafeInfoMapper.insertStaffsafeInfo(staffsafeInfo);
        insertTStaffType(staffsafeInfo);
        return rows;
    }

    /**
     * 修改培训档案人员信息
     * 
     * @param staffsafeInfo 培训档案人员信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateStaffsafeInfo(StaffsafeInfo staffsafeInfo)
    {
//        staffsafeInfoMapper.deleteStaffsafeInfoById(staffsafeInfo.getId());
//        insertTStaffType(staffsafeInfo);
        //先查询是否有对应的type  有则更新 无则新增
        StaffsafeInfo param = new StaffsafeInfo();
        param.setId(staffsafeInfo.getId());
        String typecode = staffsafeInfo.getTypeCode();
        if(StringUtils.isNotEmpty(typecode)){
            List<StaffsafeInfo> staffsafeInfos = staffsafeInfoMapper.selectStaffsafeInfoList(param);
            for (StaffsafeInfo info : staffsafeInfos) {
                StaffType staffType = info.getStaffType();
                if(null != staffType){
                    staffType.setTypecode(typecode);
                    return staffTypeMapper.updateStaffType(staffType);
                }else{
                    if(StringUtils.isNotEmpty(typecode)){
                        String uuid = IdGen.uuid();
                        StaffType pst = new StaffType();
                        pst.setId(uuid);
                        pst.setTypecode(typecode);
                        pst.setUserid(staffsafeInfo.getId());
                        return staffTypeMapper.insertStaffType(pst);
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 批量删除培训档案人员信息
     * 
     * @param ids 需要删除的培训档案人员信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteStaffsafeInfoByIds(String[] ids)
    {
        staffsafeInfoMapper.deleteStaffsafeInfoByIds(ids);
        return staffsafeInfoMapper.deleteStaffsafeInfoByIds(ids);
    }

    /**
     * 删除培训档案人员信息信息
     * 
     * @param id 培训档案人员信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteStaffsafeInfoById(String id)
    {
        staffsafeInfoMapper.deleteStaffTypeByUserId(id);
        return staffsafeInfoMapper.deleteStaffsafeInfoById(id);
    }

    /**
     * 新增培训档案人员类型信息
     * 
     * @param staffsafeInfo 培训档案人员信息对象
     */
    public void insertTStaffType(StaffsafeInfo staffsafeInfo)
    {
        StaffType staffType = staffsafeInfo.getStaffType();
        String id = staffsafeInfo.getId();
        if (StringUtils.isNotNull(staffType))
        {
            List<StaffType> list = new ArrayList<StaffType>();

                staffType.setUserid(id);
                list.add(staffType);

            if (list.size() > 0)
            {
                staffsafeInfoMapper.batchStaffType(list);
            }
        }
    }
}
